# -*- coding: utf-8 -*-

from qgis.core import (
    QgsGeometry,
    QgsWkbTypes,
    Qgis
)

from qgis.gui import (
    QgsRubberBand,
    QgsMapToolEmitPoint,
    QgsMapMouseEvent
)

from PyQt5.QtCore import Qt,pyqtSignal
from PyQt5.QtGui import QColor

class DrawingPolygonTool(QgsMapToolEmitPoint):
    # 绘制信号
    # str 绘制行为
    # Qgis.GeometryType 绘制类型
    # QgsGeometry 绘制图形容器
    drawGeometry = pyqtSignal(str,Qgis.GeometryType,QgsGeometry)

    def __init__(self,action, canvas):
        super().__init__(canvas)
        self.__action = action
        self.__canvas = canvas
        self.__crs = canvas.mapSettings().destinationCrs()

        self.__points = []
        
        self.__line_rubber_band = QgsRubberBand(self.__canvas, QgsWkbTypes.LineGeometry)
        self.__line_rubber_band.setColor(Qt.blue)
        self.__line_rubber_band.setWidth(2)

        self.__point_rubber_band = QgsRubberBand(self.__canvas, QgsWkbTypes.PointGeometry)
        self.__point_rubber_band.setColor(Qt.red)
        self.__point_rubber_band.setWidth(2)
        

    def __drawGeometry(self):
        # 检查图形是否是一个闭合的多边形，如果不是，则添加一个点来封闭多边形
        if self.__points[0] != self.__points[-1]:
            self.__points.append(self.__points[0])

        #将点集转换为图形
        geomtry = QgsGeometry.fromPolygonXY([self.__points])

        # 将图形通过signal信号发送到接收端
        self.drawGeometry.emit(self.__action,Qgis.GeometryType.Polygon,geomtry)

        # 将图形容器从画布中移除
        # self.__canvas.scene().removeItem(rubber_band)

        self.__clear()

    def __clear(self):
        # 清除缓存
        self.__points.clear()
        self.__line_rubber_band.reset(QgsWkbTypes.LineGeometry)
        self.__point_rubber_band.reset(QgsWkbTypes.PointGeometry)

    def canvasPressEvent(self, e):
        # e.isAccepted() 验证按钮是否被接收，添加了此判断之后勾绘会有卡顿
        # if e.button() == Qt.LeftButton and e.isAccepted():
        if e.button() == Qt.LeftButton:
            self.__points.append(e.mapPoint())
            self.__line_rubber_band.addPoint(e.mapPoint())
            self.__point_rubber_band.addPoint(e.mapPoint())
        elif e.button() == Qt.RightButton:
            if len(self.__points) > 2:
                # 绘制图形并发送
                self.__drawGeometry()
            else:
                # 清除缓存
                self.__clear()
    
    def canvasDoubleClickEvent(self, e: QgsMapMouseEvent):
        if e.button() == Qt.LeftButton and len(self.__points) > 2:
            self.__drawGeometry()

    def deactivate(self):
        del self.__line_rubber_band
        del self.__point_rubber_band
        del self.__points
        super().deactivate()
